/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.serviceapp.service.organization.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.PrintSettingOrder;
import com.qinyeit.serviceapp.entity.PrintSettingOrderData;
import com.qinyeit.serviceapp.entity.PrintSettingOrderDetail;
import com.qinyeit.serviceapp.entity.PrintSettingOrderTableData;
import com.qinyeit.serviceapp.entity.enums.PrintSettingOrderType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.repository.organization.PrintSettingOrderRepository;
import com.qinyeit.serviceapp.service.organization.PrintSettingOrderDataService;
import com.qinyeit.serviceapp.service.organization.PrintSettingOrderDetailService;
import com.qinyeit.serviceapp.service.organization.PrintSettingOrderService;
import com.qinyeit.serviceapp.service.organization.PrintSettingOrderTableDataService;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.repository.jdbc.PageNamedParameterJdbcTemplate;
import com.qinyetech.springstage.core.service.BaseService;
import com.qinyetech.springstage.core.utils.JSONUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/** 
 * ClassName: PrintSettingOrderServiceImpl <br/> 
 * Function: 单据打印设置 业务实现 <br/> 
 * date: 2019-03-04 16:15:43 <br/> 
 * 
 * @author liuwenjin
 * @version 1.0
 * @since JDK 1.8
 */
@Service
@Transactional
public class PrintSettingOrderServiceImpl extends BaseService<PrintSettingOrder, Long> implements PrintSettingOrderService {


	@Autowired
	private PrintSettingOrderRepository printSettingOrderRepository;
	@Autowired
	private PrintSettingOrderDetailService printSettingOrderDetailService;
	@Autowired
	private PrintSettingOrderTableDataService printSettingOrderTableDataService;
	@Autowired
	private PrintSettingOrderDataService printSettingOrderDataService;
	@Autowired
	private PageNamedParameterJdbcTemplate jdbcTemplate;


    @Override
    public QyMap getPrintSettings(Long merchantGroupId) {
        //获取打印设置类型  系统在创建账号初始化的时候会将默认打印设置保存一份
        Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
        List<PrintSettingOrder> orderList = this.findWithSort(searchable);
        if(CollectionUtils.isEmpty(orderList)){
            throw new BusinessRunTimeException("打印配置信息为空",10001);
        }
        //打印设置
        QyMap map = QyMap.NEW();
        QyMap param = null;
        for (PrintSettingOrder printOrder : orderList) {
            param = QyMap.map("printType",printOrder.getPrintType())
                    .setv("name",printOrder.getName());
            searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
            searchable.addSearchParam("printSettingOrder.id_eq",printOrder.getId());
            PrintSettingOrderDetail details = printSettingOrderDetailService.findOne(searchable);
            param.setv("detailTitle",details.getTitle())
                    .setv("detailOrderExplain",details.getOrderExplain());

            searchable.addSearchParam("dataControle_eq",1);
            List<PrintSettingOrderData> dataList = printSettingOrderDataService.findWithSort(searchable);
            dataList.stream().sorted((x1,x2)->x1.getWeight().compareTo(x2.getWeight())).collect(Collectors.toList());
            param.setv("dataSet",JSONUtils.include(dataList,"name","code","hasPrint"));

            List<PrintSettingOrderTableData> tableDataList = printSettingOrderTableDataService.findWithSort(searchable);
            tableDataList.stream().sorted((x1,x2)->x1.getWeight().compareTo(x2.getWeight())).collect(Collectors.toList());
            param.setv("tableDataSet",JSONUtils.include(tableDataList,"name","code","hasPrint"));
            map.setv(printOrder.getPrintType().getKey(),param);
        }
        return map;
    }

    @Override
    public boolean saveData(JSONObject data, Long merchantGroupId) {
        if(data==null){
            return false;
        }
        Searchable searchable = null;

        // 获取商户表单设置打印信息
        PrintSettingOrderType printType = PrintSettingOrderType.getByString(data.getString("printType"));
        if(printType==null){
            return false;
        }

        String title = data.getString("title");
        String orderExplain = data.getString("orderExplain");
        if(StringUtils.isNotBlank(orderExplain)){
            orderExplain = orderExplain.trim();
        }
        //打印动态数据
        JSONArray dataSetArr = data.getJSONArray("dataSet");
        JSONArray tableDataArr = data.getJSONArray("dataTable");

        // 获取数据库打印设置
        searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
        searchable.addSearchParam("printType_eq", printType);
        PrintSettingOrder printSettingOrder = super.findOne(searchable);
        if(printSettingOrder==null){
            return false;
        }

        //更新配置
        String sql = "update print_setting_order_details set title=:title, order_explain=:order_explain where print_setting_order_id=:print_setting_order_id";
        QyMap params = QyMap.map("title",title)
                .setv("order_explain",orderExplain)
                .setv("print_setting_order_id",printSettingOrder.getId());
        jdbcTemplate.update(sql,params);

        sql = "update print_setting_order_datas set is_print=0 where print_setting_order_id=:print_setting_order_id and data_controle=1";
        params = QyMap.map("print_setting_order_id",printSettingOrder.getId());
        jdbcTemplate.update(sql,params);

        sql = "update print_setting_order_datas set is_print=1 where print_setting_order_id=:print_setting_order_id and data_controle=1 and code in (:code)";
        params = QyMap.map("print_setting_order_id",printSettingOrder.getId())
                .setv("code",dataSetArr);
        jdbcTemplate.update(sql,params);

        sql = "update print_setting_order_table_datas set is_print=1 where print_setting_order_id=:print_setting_order_id and data_controle=1 and code in (:code)";
        params = QyMap.map("print_setting_order_id",printSettingOrder.getId())
                .setv("code",tableDataArr);
        jdbcTemplate.update(sql,params);
        return true;
    }

    @Override
    public QyMap getPrintSettingsByType(PrintSettingOrderType printType, Long merchantGroupId) {
        Searchable searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
        searchable.addSearchParam("printType_eq",printType);
        PrintSettingOrder printOrder = this.findOne(searchable);
        if(printOrder==null){
            throw new BusinessRunTimeException("打印配置信息为空",10001);
        }
        //打印设置
        QyMap param = null;
        param = QyMap.map("printType",printOrder.getPrintType())
                .setv("name",printOrder.getName());
        searchable = SearchUtils.newSearchableWithMerchantFilter(merchantGroupId);
        searchable.addSearchParam("printSettingOrder.id_eq",printOrder.getId());
        PrintSettingOrderDetail details = printSettingOrderDetailService.findOne(searchable);
        param.setv("detailTitle",details.getTitle())
                .setv("detailOrderExplain",details.getOrderExplain());
        searchable.addSearchParam("dataControle_eq",1);
        List<PrintSettingOrderData> dataList = printSettingOrderDataService.findWithSort(searchable);
        dataList.stream().sorted((x1,x2)->x1.getWeight().compareTo(x2.getWeight())).collect(Collectors.toList());
        param.setv("dataSet",JSONUtils.include(dataList,"name","code","hasPrint"));
        List<PrintSettingOrderTableData> tableDataList = printSettingOrderTableDataService.findWithSort(searchable);
        tableDataList.stream().sorted((x1,x2)->x1.getWeight().compareTo(x2.getWeight())).collect(Collectors.toList());
        param.setv("tableDataSet",JSONUtils.include(tableDataList,"name","code","hasPrint"));
        return param;
    }
}